﻿//方法一：贪心
var minStartValue = function (nums) {
    let accSum = 0, accSumMin = 0;
    for (const num of nums) {
        accSum += num;
        accSumMin = Math.min(accSumMin, accSum);
    }
    return -accSumMin + 1;
};


//方法二：二分查找
var minStartValue = function (nums) {
    const m = _.min(nums);
    if (m >= 0) {
        return 1;
    }
    let left = 1, right = -m * nums.length + 1;
    while (left < right) {
        const medium = Math.floor((left + right) / 2);
        if (valid(medium, nums)) {
            right = medium;
        } else {
            left = medium + 1;
        }
    }
    return left;
};

const valid = (startValue, nums) => {
    for (const num of nums) {
        startValue += num;
        if (startValue <= 0) {
            return false;
        }
    }
    return true;
}
